#include "videoreolaywidget.h"
#include <QVideoWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>

VideoReolayWidget::VideoReolayWidget(QString path,QWidget *parent) : QWidget(parent)
{
    this->path=path;
    this->initUI();
    this->resize(600, 700);
}

//VideoReolayWidget::~VideoReolayWidget()
//{
//    delete title;
//    delete ret_button;
//    delete begin_video;
//    delete mediaPlayer;
//    delete videoWidget;
//}

void VideoReolayWidget::initUI()
{

    this->con=MyControl::getInstance();
    this->title = new QLabel("录像回放界面");
    this->title->setStyleSheet(
            "QLabel {"
            "    background-color: #f0f0f0;"         // 背景色
//            "    border: 2px solid #333;"           // 边框
//            "    border-radius: 10px;"              // 圆角
            "    padding: 8px 16px;"                // 内边距
            "    font-size: 40px;"                  // 字体大小
            "    font-weight: bold;"                // 加粗
            "    color: #333;"                     // 字体颜色
            "    text-align: center;"               // 文本居中
            "    margin-bottom: 15px;"              // 底部边距
            "}"
        );
    this->ret_button = new QPushButton(QIcon("../image_tool/return-button.png"),"");
    this->begin_video = new QPushButton("播放");
    this->screen=new QLabel();
    this->image=new QPixmap();
    this->screen->setPixmap(*image);

    this->seekSlider=new QSlider(Qt::Horizontal,this);
    this->seekSlider->setStyleSheet(
            "QSlider::groove:horizontal {"
            "    border: 1px solid #bbb;"
            "    background: white;"
            "    height: 10px;"
            "    border-radius: 4px;"
            "}"
            "QSlider::sub-page:horizontal {"
            "    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,"
            "                                stop: 0 #66e, stop: 1 #bbf);"
            "    background: qlineargradient(x1: 0, y1: 0.2, x2: 1, y2: 1,"
            "                                stop: 0 #bbf, stop: 1 #55f);"
            "    border: 1px solid #777;"
            "    height: 10px;"
            "    border-radius: 4px;"
            "}"
            "QSlider::add-page:horizontal {"
            "    background: #fff;"
            "    border: 1px solid #777;"
            "    height: 10px;"
            "    border-radius: 4px;"
            "}"
            "QSlider::handle:horizontal {"
            "    background: qlineargradient(x1:0, y1:0, x2:1, y2:1,"
            "                                stop:0 #eee, stop:1 #ccc);"
            "    border: 1px solid #777;"
            "    width: 13px;"
            "    margin-top: -2px;"
            "    margin-bottom: -2px;"
            "    border-radius: 4px;"
            "}"
            "QSlider::handle:horizontal:hover {"
            "    background: qlineargradient(x1:0, y1:0, x2:1, y2:1,"
            "                                stop:0 #fff, stop:1 #ddd);"
            "}"
            "QSlider::sub-page:horizontal:disabled {"
            "    background: #bbb;"
            "    border-color: #999;"
            "}"
            "QSlider::add-page:horizontal:disabled {"
            "    background: #eee;"
            "    border-color: #999;"
            "}"
            "QSlider::handle:horizontal:disabled {"
            "    background: #eee;"
            "    border: 1px solid #aaa;"
            "    border-radius: 4px;"
            "}"
        );


    playBtn = new QPushButton(QIcon("../image_tool/play-button.png"), "");
    prevBtn = new QPushButton(QIcon("../image_tool/arrow.png"), "");
    nextBtn = new QPushButton(QIcon("../image_tool/next-button.png"), "");
    clipBtn = new QPushButton(QIcon("../image_tool/scissors.png"), "");
    speedCombo = new QComboBox;
    speedCombo->addItems({"1倍速", "0.5倍速", "1.5倍速", "2倍速"});






    this->layout_H1 = new QHBoxLayout();
    this->layout_H2 = new QHBoxLayout();
    this->layout_H3 = new QHBoxLayout();
    this->layout_H4 = new QHBoxLayout();
    this->layout_H5 = new QHBoxLayout();
    this->video_layoutV = new QVBoxLayout();
    this->layout_V = new QVBoxLayout();


    QHBoxLayout *controlLayout = new QHBoxLayout;
    controlLayout->addWidget(prevBtn);
    controlLayout->addWidget(playBtn);
    controlLayout->addWidget(nextBtn);
    controlLayout->addStretch();
    controlLayout->addWidget(speedCombo);
    controlLayout->addWidget(clipBtn);



    // 设置布局的间距和对齐方式
    layout_H1->setAlignment(Qt::AlignCenter);
    layout_H2->setAlignment(Qt::AlignLeft);
//    layout_V->setSpacing(20);
//    layout_V->setContentsMargins(20, 20, 20, 20);

    this->layout_H1->addWidget(title);
    this->layout_H2->addWidget(ret_button);
    this->layout_H3->addWidget(screen);
    this->layout_H4->addWidget(seekSlider);


    this->layout_V->addLayout(layout_H1);
    this->layout_V->addLayout(layout_H2);
    this->layout_V->addLayout(layout_H3);
    this->layout_V->addLayout(layout_H4);

    this->layout_V->addLayout(controlLayout);
    this->layout_V->setContentsMargins(30,30,30,30);



    this->screen->setMinimumSize(600,600);  // 宽x高，根据布局调整
    this->screen->setMaximumSize(600,600);
    this->screen->setAlignment(Qt::AlignCenter);  // 文本居中
    this->screen->setStyleSheet("QLabel {"
                            "border: 2px solid black;"  // 2 像素宽的黑色实线边框
                            "border-radius: 5px;"      // 边框圆角半径为 5 像素
                            "padding: 10px;"           // 内边距为 10 像素
                            "}");

    this->setLayout(layout_V);
    // 连接信号与槽
    this->decode2=new DecodeVideo();
    this->decode2->setFilepath(path);

    connect(this->ret_button,&QPushButton::clicked,this,&VideoReolayWidget::RetToSelect);
    connect(this->playBtn,&QPushButton::clicked,this,&VideoReolayWidget::begin);
    connect(this->decode2,&DecodeVideo::sendImage,this,&VideoReolayWidget::reciverImage);
    connect(this->clipBtn,&QPushButton::clicked,this,&VideoReolayWidget::clipImage);
    connect(this->speedCombo,&QComboBox::currentTextChanged,this,&VideoReolayWidget::onComboBoxIndexChanged);
    connect(this->nextBtn,&QPushButton::clicked,this,&VideoReolayWidget::onNextCliked);
    connect(this->prevBtn,&QPushButton::clicked,this,&VideoReolayWidget::onPrevCliked);
    connect(this->ret_button,&QPushButton::clicked,this,&VideoReolayWidget::ret);
   // connect(this->seekSlider,&QSlider::valueChanged,this,&VideoReolayWidget::onSeekSliderValueChanged);
//这里想写拖动进度条可以移动到相应的播放的位置的，发现不行，后面有时间和思路再解决


}

void VideoReolayWidget::RetToSelect()
{
    emit ToSelect();
}

void VideoReolayWidget::clipImage()
{
    QImage printscreen=this->image->toImage();
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString timeStr = currentDateTime.toString("yyyy-MM-dd-hh-mm-ss");
    QString fullFileName ="../image/"+timeStr+".png";
    printscreen.save(fullFileName.toStdString().c_str());

    //计算图片大小
    QString imageFilePath =fullFileName;
    QFileInfo fileInfo(imageFilePath);
     double sizeInKB;
    if (fileInfo.exists())
    {
            // 获取文件大小（单位：字节）
     qint64 fileSize = fileInfo.size();
     qDebug() << "图片文件大小（字节）：" << fileSize;

            // 转换为更易读的单位（KB）
     sizeInKB = static_cast<double>(fileSize) / 1024;
     qDebug() << "图片文件大小（KB）：" << sizeInKB;
    }else
     {
     qDebug() << "图片文件不存在。";
     }


    //保存数据库
    this->model=this->con->getModel("Image_file");
    QString sql=QString("insert into image_files (user_id,image_path,image_name,image_size,image_time) values(%1,'%2','%3','%4','%5');")
            .arg(id)
            .arg(fullFileName.toStdString().c_str())
            .arg(timeStr.toStdString().c_str())
            .arg((int)sizeInKB)
            .arg(timeStr.toStdString().c_str());
    qDebug()<<sql;
    this->model->sqlInstruct((char *)sql.toStdString().c_str());

    QMessageBox::information(this,"提示","截图成功");
}

void VideoReolayWidget::onComboBoxIndexChanged(const QString &text)
{

    qDebug() << "当前解码速度: " << this->decode2->getSpeed();
    QString speedNumberStr = text;
    speedNumberStr = speedNumberStr.remove("倍速");
    qDebug() << "提取的速度字符串: " << speedNumberStr;

    float speedFactor = speedNumberStr.toFloat();
    if (speedFactor == 0.0) {
        qDebug() << "速度转换失败，请检查输入字符串。";
        return;
    }

    //倒数转换
    float invertedSpeedFactor = 1.0 / speedFactor;
    float newSpeed = this->decode2->getPrevSpeed() * invertedSpeedFactor;
    this->setSpeed(newSpeed);
    qDebug() << "新的解码速度: " << newSpeed;
    this->decode2->setSpeed(newSpeed);

//    decode2->setIsStop(true);
//    decode2->wait();
//    decode2->setIsStop(false);
//    decode2->start(); // 重新启动线程
}

void VideoReolayWidget::onNextCliked()
{
    //这里直接退出循环
    this->decode2->setSt(true);//退出事件循环
    this->decode2->wait();
    qDebug()<<"线程退出";


    //设置各个参数
    this->isPlay=false;
    this->isFirstplay=false;
    this->playBtn->setIcon(QIcon("../image_tool/play-button.png"));


    // 重置进度条
    st1 = 1;
    seekSlider->setValue(0); // 回到原点
    this->x=0;

    // 更新当前视频的索引
       videoIndex++;
       if (videoIndex >= list.size()) {
           // 如果已经是最后一个视频，可以选择回到第一个视频或者不做处理
           videoIndex = 0;
       }

       QString path=list[videoIndex]->getVideo_path();
       qDebug()<<path;
       // 设置新的视频路径
         this->decode2->setFilepath(path);
         this->decode2->setX(0);
         this->decode2->setSt(false);



}

void VideoReolayWidget::onPrevCliked()
{
    //这里直接退出循环
    this->decode2->setSt(true);//退出事件循环
    this->decode2->wait();
    qDebug()<<"线程退出";


    //设置各个参数
    this->isPlay=false;
    this->isFirstplay=false;
    this->playBtn->setIcon(QIcon("../image_tool/play-button.png"));


    // 重置进度条
    st1 = 1;
    seekSlider->setValue(0); // 回到原点
    this->x=0;

    // 更新当前视频的索引
      if(videoIndex>=1)
       videoIndex--;

      QString path=list[videoIndex]->getVideo_path();
      qDebug()<<path;
      // 设置新的视频路径
        this->decode2->setFilepath(path);
        this->decode2->setX(0);
        this->decode2->setSt(false);

}

void VideoReolayWidget::ret()
{
    this->decode2->setIsStop(true);
    this->decode2->setX(0);
    this->decode2->setTotalFrames(0);
    emit ToSelect();
}


float VideoReolayWidget::getSpeed() const
{
    return speed;
}

void VideoReolayWidget::setSpeed(float value)
{
    speed = value;
}

int VideoReolayWidget::getVideoIndex() const
{
    return videoIndex;
}

void VideoReolayWidget::setVideoIndex(int value)
{
    videoIndex = value;
}

QList<Video *> VideoReolayWidget::getList() const
{
    return list;
}

void VideoReolayWidget::setList(const QList<Video *> &value)
{
    list = value;
}

QString VideoReolayWidget::getPath() const
{
    return path;
}

void VideoReolayWidget::setPath(const QString &value)
{
    path = value;
}

void VideoReolayWidget::begin()
{
       //this->decode2->setSt(false);
       if(this->isPlay==false)//如果没有播放,点击就开始播放
       {
           qDebug()<<"isFirstplay"<<isFirstplay;
           if(!isFirstplay)
           {
                this->decode2->setIsStop(false);
                this->decode2->setSt(false);
                this->decode2->start();
                this->isFirstplay=true;
           }//如果是第一次播放，也就是进度条在原点的时候
           this->decode2->setIsStop(false);
           this->playBtn->setIcon(QIcon("../image_tool/pause.png"));
           this->isPlay=true;//下次点击就是暂停
       }
       else//如果播放了,点击就暂停播放
       {
           this->decode2->setIsStop(true);//先暂停
           this->playBtn->setIcon(QIcon("../image_tool/play-button.png"));
           this->isPlay=false;//现在没有播放,下次点击就是播放
       }








}


void VideoReolayWidget::reciverImage(QImage img,int x)
{
    if(st1)
    {
        st1=0;
        seekSlider->setRange(0,list[this->videoIndex]->getDuration()-24);
        qDebug()<<list[this->videoIndex]->getDuration()<<"=list[this->videoIndex]->getDuration() ";
    }
       *(this->image)=QPixmap::fromImage(img);
        this->x=x;
       qDebug()<<"进度条的x="<<x;

       this->update();
}

void VideoReolayWidget::paintEvent(QPaintEvent *event)
{
   if(image)
   {
       this->screen->setPixmap(*image);
       if(this->seekSlider)
       {
           if(this->x>=list[this->videoIndex]->getDuration()-22)
           {
              this->decode2->setX(0);
              this->x=0;
              this->playBtn->setIcon(QIcon("../image_tool/play-button.png"));
              this->isPlay=false;
              this->isFirstplay=false;

           }

           this->seekSlider->setValue(x);
       }
   }
}
